package com.bridgeintelligent.tag.webserver.dim.query.service.thread;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.bridgeintelligent.tag.webserver.dim.query.api.ThemeDetailResult;
import com.bridgeintelligent.tag.webserver.dim.query.api.ThemeQueryModel;
import com.bridgeintelligent.tag.webserver.dim.query.service.QueryApi;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Slf4j
@AllArgsConstructor
public class ThemeWriteThread implements Runnable {

    private static Object obj = new Object();

    //CountDownLatch
    private CountDownLatch countDownLatch;
    //类型
    private int i;

    private Integer sheetNum;

    private Integer ROW_SIZE;

    private Integer oneSheetWriteCount;

    private Integer lastSheetWriteCount;

    private List<List<String>> head;

    private ThemeQueryModel themeQueryModel;

    private Integer WRITE_SIZE ;

    private QueryApi queryApi;

    private ExcelWriter excelWriter;


    /**
     * 线程任务，批量处理数据
     */
    @Override
    public void run() {
        try {
            long time = System.currentTimeMillis()/1000;
            //创建Sheet
            WriteSheet sheet = new WriteSheet();
            sheet.setSheetName("Sheet"+i);
            sheet.setSheetNo(i);
            //循环写入次数: j的自增条件是当不是最后一个Sheet的时候写入次数为正常的每个Sheet写入的次数,如果是最后一个就需要使用计算的次数lastSheetWriteCount
            for (int j = 0; j < (i != sheetNum - 1 ? oneSheetWriteCount : lastSheetWriteCount); j++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i, "Sheet" + (i + 1)).head(head)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
                themeQueryModel.setFrom(i * ROW_SIZE + j * WRITE_SIZE);
                log.info(Thread.currentThread().getName()+"线程处理第:"+i+"个sheet页第:"+j+"次数据从:"+(i * ROW_SIZE + j * WRITE_SIZE)+"位置开始");
                ThemeDetailResult result =  queryApi.themeDetail(JSON.toJSONString(themeQueryModel));
                if (result != null && result.getCode() == 0 && result.getData() != null){
                    synchronized ( obj ) {
                        excelWriter.write(handResult(themeQueryModel,result.getData().getContent()), writeSheet);
                    }
                }
            }
            log.info("处理第"+i+"sheet耗时:"+(System.currentTimeMillis()/1000-time));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //计数器减1
            countDownLatch.countDown();
        }
    }

    private List<List<String>>  handResult(ThemeQueryModel themeQueryModel, List<Map<String, String>> data){
        List<String> fields = themeQueryModel.getFields();
        Map<String,String> fieldMap = themeQueryModel.getFieldMap();

        List<List<String>> list = new ArrayList<>();
        List<String> rowDate  = null;
        for (Map<String, String> map :data ) {
            rowDate = new ArrayList<>(fields.size());
            for (String field:fields) {
                if ("cust_id".equals(field)){
                    rowDate.add(map.get(field));
                }else{
                    rowDate.add(map.get(fieldMap.get(field)));
                }
            }
            list.add(rowDate);
        }
        return list;
    }
}
